<template>
    <a-card :bordered="false" style="min-height: 70vh;width: 100%;">
        <!-- <div class="table-page-search-wrapper">
            <a-form layout="inline">
                <a-row style="display: flex;position: absolute;right: 20px;">
                    <a-col :md="24" :sm="24">
                        日期区间:{{ startRange }}{{ endRange ? '~' : '' }}{{ endRange }}
                    </a-col>
                </a-row>
                <a-row :gutter="10">
                    <a-col :md="3" :sm="24">
                        <a-form-item label="客户">
                            <a-input v-model="queryParam.Name" placeholder="请输入客户" @keydown.enter="getDataList" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="4" :sm="24">
                        <a-form-item label="产品名称">
                            <a-input v-model="queryParam.Product" placeholder="请输入产品名称" @keydown.enter="getDataList" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="17" :sm="24">
                        <a-select style="width: 100px;margin-left: 8px;" v-model="selectTime" @change="changeTime"
                            name="radioGroup" :default-value="0">
                            <a-select-option :value="index" v-for="(i, index) in ['一个月', '三个月', '六个月', '自定义']" :key="i">
                                {{ i }}
                            </a-select-option>
                        </a-select>
                        <a-range-picker style="width: 220px;margin-left: 8px;" :placeholder="['开始月份', '结束月份']"
                            format="YYYY-MM" :value="time" :mode="['month', 'month']" :open="monthPickShow"
                            @panelChange="handlePanelChange2" :disabled="timeDisabled" @openChange="handleOpenChange" />
                        <a-button style="margin-left: 10px;" type="primary"
                            @click="() => { showSpecial  = true}">特殊单据<span style="padding: 2px 8px;background: red;margin-left: 3px; border-radius: 20px;" v-show="selectRowsData.length>0">{{
                                selectRowsData.length }}</span>
                        </a-button>
                        <a-button style="margin-left: 10px;" type="primary" @click="() => {
        this.pagination.current = 1
        this.getDataList()
        this.abc()
    }   
        ">查询
                        </a-button>
                        <a-button style="margin-left: 8px;margin-right: 8px;" @click="repossess">重置</a-button>
                        <a-button type="primary" icon="download" @click="downloadTemplate">导出</a-button>
                    </a-col>
                </a-row>
            </a-form>
        </div> -->

        <table v-if="a" style="width: 100%;min-height: 70vh;">
            <tr style="display:flex;width:100vw;">
                <td style="display:flex;flex-direction: column;align-items: center;width: 250px;  min-height: 70vh;">
                    <!-- <a-button ref="btn" style="min-width:100%;" type="primary" @click="() => {
        this.pagination.current = 1
        this.getDataList()
        this.abc()
    }
        ">配置数据源
                    </a-button> -->
                    <JqxPivotDesigner style="width: 250px;  min-height: 95vh;" ref="pivotDesigner" :type="'pivotGrid'">

                    </JqxPivotDesigner>

                </td>
                <td style="max-width:500px">
                    <JqxPivotGrid @rowexpand="onRowexpand($event)" style="max-width:85vw;min-height:95vh"
                        :groupsexpandedbydefault="true" ref="pivotGrid" :scrollBarsEnabled="false" :source="pivotDataSource"
                        :autoResize="true">
                    </JqxPivotGrid>
                </td>
            </tr>
        </table>
        <!-- <a-modal :visible="showSpecial" width="80%" @cancel="() => { showSpecial = false}" @ok="selectSpecial">
            <Special ref="special"></Special>
        </a-modal> -->
        <div v-else style="display:flex;justify-content: center;align-items: center;">
            <img src="@/assets/load.gif" />
        </div>
    </a-card>
</template>

<script>
// import Special from "./special.vue"
import JqxPivotGrid from 'jqwidgets-scripts/jqwidgets-vue/vue_jqxpivotgrid.vue';
import JqxPivotDesigner from 'jqwidgets-scripts/jqwidgets-vue/vue_jqxpivotdesigner.vue';
import moment from 'moment'
const columns = [
    { title: '业务员', dataIndex: 'Title', },
    { title: '产品名称', dataIndex: 'InventoryName', },
    { title: '产品编号', dataIndex: 'InventoryCode', },
    { title: '规格', dataIndex: 'Inventoryspec', },
    { title: '仓库', dataIndex: 'WarehouseName', },
    // { title: '计量单位', dataIndex: 'Inventoryunit', width: '80px' },
    { title: '数量', dataIndex: 'InvoicingQuantity', align: 'right', width: '100px' },
    { title: '销售金额', dataIndex: 'InvoicingAmount', align: 'right', width: '100px' },
    { title: '成本单价', dataIndex: 'CostPrice', align: 'right', width: '100px' },
    { title: '成本', dataIndex: 'CostAmount', align: 'right', width: '100px' },
    { title: '毛利', dataIndex: 'GrossProfit', align: 'right', width: '100px' },
    { title: '状态', dataIndex: 'Status', align: 'right', width: '100px' },
    // { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, }
]
export default {
    components: {
        JqxPivotGrid,
        JqxPivotDesigner,
        // Special
    },
    computed: {
        startRange() {
            if (!this.time[0]) {
                return ''
            }
            const currentDate = new Date(this.time[0]); // 获取当前日期
            const previousMonth = (currentDate.getMonth() === 0) ? 12 : currentDate.getMonth(); // 如果当前月份是1月，则上个月是12月，否则上个月就是当前月份减一
            return `${currentDate.getMonth() === 0 ? new Date().getFullYear(this.time[0]) - 1 : new Date().getFullYear(this.time[0])}-${previousMonth}-26`
        },
        endRange() {
            if (!this.time[1]) {
                return ''
            }
            const currentDate = new Date(this.time[1]); // 获取当前日期
            const previousMonth = currentDate.getMonth() + 1; // 如果当前月份是1月，则上个月是12月，否则上个月就是当前月份减一
            return `${new Date().getFullYear(this.time[1])}-${previousMonth}-25`
        }
    },
    data: function () {
        return {
            pivotDataSource: this.pivotDataSource,
            pagination: {
                current: 1,
                pageSize: 100000,
                showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
                pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
                showSizeChanger: true
            },
            queryParam: { Warehouse: '02' },
            data: [],
            ab: false,
            monthPickShow: false,
            a: false,
            columns,
            timeDisabled: true,
            time: [],
            selectTime: 0,
            showSpecial: false,
            selectRowsData: [],
        }
    },
    created: function () {
        this.pivotDataSource = null;
    },
    mounted: function () {
        this.$nextTick(() => {
            // 页面渲染完成后的回调
            // this.tableHeight = this.getTableHeight(true) + 24
            this.time = [this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))]
            this.getDataList()
            // this.getSelectOptions();
        })
        // let pivotGridComponent = this.$refs.pivotGrid;
        // let pivotGridInstance = pivotGridComponent.getInstance();

        // this.$refs.pivotDesigner.target = pivotGridInstance;
        // this.$refs.pivotDesigner.refresh();
    },
    methods: {
        onRowexpand: function (event) {
            alert('do something...');
        },
        selectSpecial() {
            this.selectRowsData = this.$refs.special.selectRows;
            this.showSpecial = false;
        },
        repossess() {
            this.queryParam = { Warehouse: '02' }
            this.changeTime(0);
            this.getDataList();
        },
        handlePanelChange2(value) {
            if (this.time[1] && this.time._d != value[1]._d) {
                this.monthPickShow = false;
            }
            this.time = value;
        },
        handleOpenChange(status) {
            if (status) {
                this.monthPickShow = true;
            } else {
                this.monthPickShow = false
            }
        },
        changeTime(e) {
            this.timeDisabled = true;
            this.selectTime = e;
            this.time = [];
            switch (e) {
                case 0:
                    this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1))
                    this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
                    break
                case 1:
                    this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 2, 1))
                    this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
                    break
                case 2:
                    this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1))
                    this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
                    break
                case 3:
                    this.timeDisabled = false;
                    break
            }
        },
        //导出
        downloadTemplate() {
            this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/ExportByCustomer', {
                Search: { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "" },
            }, { responseType: 'blob' }).then(res => {
                const url = URL.createObjectURL(res)
                // console.log(url)
                const fileName = '业务员毛利分析表'
                const aTag = document.createElement('a')
                aTag.download = fileName
                aTag.href = url
                aTag.click()
                URL.revokeObjectURL(aTag.href)
            }).catch(err => {
                this.$message.error(err);
            })
        },
        getDataAll() {
            this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GetGrossProfitTotalByCustomer', { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "" }).then(res => {
                if (res.Success) {
                    this.entity = res.Data;
                }
            }).catch(err => {
                this.$message.error(err);
            })
        },
        abc() {
            this.a = true;
            this.ab = true;
            this.pivotDataSource = this.createPivotDataSource(this.data);

            this.$nextTick(() => {
                let pivotGridComponent = this.$refs.pivotGrid;
                let pivotGridInstance = pivotGridComponent.getInstance();
                pivotGridInstance.getPivotRows().items.forEach(item => {
                    // item.expand()
                    // item.isExpanded = true;
                    recursion(item.items)
                })
                function recursion(item) {
                    item.forEach(ite => {
                        // ite.expand();
                        ite.isExpanded = true;
                        if (ite.items.length > 0) {
                            recursion(ite.items)
                        }
                    })
                }
                this.$refs.pivotDesigner.target = pivotGridInstance;
                this.$refs.pivotDesigner.refresh();
                pivotGridInstance.getPivotRows().refresh();
            })

        },
        createPivotDataSource(body) {
            console.log(body)
            const columns = [
                { title: '业务员', dataIndex: 'Title', },
                { title: '产品名称', dataIndex: 'InventoryName', },
                { title: '产品编号', dataIndex: 'InventoryCode', },
                { title: '规格', dataIndex: 'Inventoryspec', },
                { title: '仓库', dataIndex: 'WarehouseName', },
                // { title: '计量单位', dataIndex: 'Inventoryunit', width: '80px' },
                { title: '数量', dataIndex: 'InvoicingQuantity', align: 'right', width: '100px' },
                { title: '销售金额', dataIndex: 'InvoicingAmount', align: 'right', width: '100px' },
                { title: '成本单价', dataIndex: 'CostPrice', align: 'right', width: '100px' },
                { title: '成本', dataIndex: 'CostAmount', align: 'right', width: '100px' },
                { title: '毛利', dataIndex: 'GrossProfit', align: 'right', width: '100px' },
                { title: '状态', dataIndex: 'Status', align: 'right', width: '100px' },
                // { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, }
            ]
            // prepare sample data
            let data = new Array();
            let datafields = [];
            for (let c = 0; c < columns.length; c++) {
                datafields.name = columns[c].title;
                datafields.type = 'string';
            }
            for (let i = 0; i < body.length; i++) {
                let row = {};
                for (let j = 0; j < columns.length; j++) {
                    row[columns[j]['title']] = body[i][columns[j]['dataIndex']]
                    
                }
                data[i] = row;
            }
            console.log(data, '168')
            // create a data source and data adapter
            let source =
            {
                localdata: data,
                datatype: "array",
                datafields: datafields,
            };
            console.log(source);
            let dataAdapter = new jqx.dataAdapter(source);
            dataAdapter.dataBind();

            // create a pivot data source from the dataAdapter
            let pivotDataSource = new jqx.pivot(
                dataAdapter,
                {
                    customAggregationFunctions: {
                        'var': function (values) {
                            if (values.length <= 1)
                                return 0;

                            // sample's mean
                            var mean = 0;
                            for (var i = 0; i < values.length; i++)
                                mean += values[i];

                            mean /= values.length;

                            // calc squared sum
                            var ssum = 0;
                            for (var i = 0; i < values.length; i++)
                                ssum += Math.pow(values[i] - mean, 2)

                            // calc the variance
                            var variance = ssum / values.length;

                            return variance;
                        }
                    },
                    pivotValuesOnRows: false,
                    rows: [{ dataField: '产品名称', text: '产品名称' }, { dataField: '业务员', text: '业务员', expanded: true }, { dataField: '仓库', text: '仓库', expanded: true }, { dataField: '规格', text: '规格' }],
                    columns: [{ dataField: '状态', text: '状态' }],
                    filters: [
                    ],
                    
                    values: [
                        { dataField: '数量', 'function': 'sum',width:250, text: '数量合计', align: 'right', formatSettings: { decimalPlaces: 4, thousandsSeparator: ',', decimalPlaces:'2', align: 'right' }, cellsClassName: 'myItemStyle', cellsClassNameSelected: 'myItemStyleSelected' },
                        { dataField: '销售金额', 'function': 'sum', width: 250, text: '销售金额合计', className: 'myItemStyle', formatSettings: { decimalPlaces: 4, thousandsSeparator: ',', decimalPlaces:'2', align: 'right' }, classNameSelected: 'myItemStyleSelected' },
                        { dataField: '成本', 'function': 'sum', width: 250, text: '成本合计', className: 'myItemStyle', formatSettings: { decimalPlaces: 4, thousandsSeparator: ',', decimalPlaces:'2', align: 'right' }, classNameSelected: 'myItemStyleSelected' },
                        { dataField: '毛利', 'function': 'sum', width: 250, text: '毛利合计', className: 'myItemStyle', formatSettings: { decimalPlaces: 4, thousandsSeparator: ',', decimalPlaces:'2', align: 'right' }, classNameSelected: 'myItemStyleSelected' }
                    ]
                },
                {},
                {
                    isExpanded:true,
                }
            );
            console.log(pivotDataSource)
            return pivotDataSource;
        },
        getDataList() {
            if (!this.time[1]) {
                this.$message.error('请先选择日期区间')
                return;
            }
            this.a = false;
            this.pivotDataSource = null;

            this.selectedRowKeys = []
            // this.queryParam.condition='name'
            this.loading = true
            this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GetCostPrice', { StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "" })
            this.$http
                .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetGrossProfitBySaler', JSON.parse(this.$route.query.data))
                .then(resJson => {
                    this.loading = false
                    this.data = resJson.Data
                    this.data.forEach(item => {
                        // item.InvoicingAmount = this.$options.filters.NumberFormats(item.InvoicingAmount)
                        // item.InvoicingQuantity = item.InvoicingQuantity.toFixed('4')
                        item.Inventoryspec = item.Inventoryspec + ' ' + item.Inventoryunit
                    })
                    // this.$refs.pivotDesigner.refresh();
                    this.abc();
                    if (this.data) {
                        const pagination = { ...this.pagination }
                        pagination.total = resJson.Total
                        this.pagination = pagination
                    }
                    this.getDataAll();
                }).catch(err => {
                    this.$message.error(err);
                })
        },
        timeFormat(val) {
            // 时间格式化函数
            return moment(val).format('YYYY-MM')
        }
    }
}
</script>

<style>
@import url('../../../../node_modules/jqwidgets-scripts/jqwidgets/styles/jqx.base.css');
@import url('../../../../node_modules/jqwidgets-scripts/jqwidgets/styles/jqx.material.css');

/* <link rel="stylesheet" href="node_modules/jqwidgets-scripts/jqwidgets/styles/jqx.base.css" type="text/css" /> */
.jqx-pivotgrid {
    background: white !important;
}

.jqx-fill-state-normal {
    background: #fff !important;
}

.jqx-pivotgrid-item {
    height: 30px !important;
}

.ant-card-body {
    padding: 0;
}

#innerDiv div {
    padding-right: 15px !important;
}
#innerDiv {
    font-size: 18px !important;
    line-height:18px !important;
    padding: 5px 0;
}
 .jqx-item {
    font-size: 16px !important;
}
</style>